﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Reflection;
using System.Web;
using System.Web.Services;
using System.Web.SessionState;

namespace HCFramework.Services
{
    /// <summary>
    /// Summary description for ExcuteServerMethod
    /// </summary>
    public class ExcuteServerMethod : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            string ret = "";

            string functionName = context.Request.QueryString["methodPath"];
            if (!string.IsNullOrEmpty(functionName))
            {
                List<object> args = new List<object>();
                string[] keys = context.Request.Form.AllKeys;
                NameValueCollection form = HttpContext.Current.Request.Form;
                for (int i = 0, length = keys.Length; i < length; i++)
                        args.Add(form[keys[i]]);
                ret = CallMethod(functionName, args.ToArray());
            }
            else
                ret = string.Empty;

            context.Response.ContentType = "text/plain";
            context.Response.Write(ret);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        public string CallMethod(string functionName, object[] args)
        {
            string typeName = functionName.Substring(0, functionName.LastIndexOf('.'));
            functionName = functionName.Substring(functionName.LastIndexOf('.') + 1);
            Type type = Type.GetType(typeName);

            MethodInfo mi = type.GetMethod(functionName);
            ParameterInfo[] pis = mi.GetParameters();
            for (int i = 0, length = pis.Length; i < length; i++)
                switch (pis[i].ParameterType.Name.ToLower())
                {
                    case "int32": args[i] = Convert.ToInt32(args[i]); break;
                    case "boolean": args[i] = Convert.ToBoolean(args[i]); break;
                    case "datetime": args[i] = Convert.ToDateTime(args[i]); break;
                    case "int64": args[i] = Convert.ToInt64(args[i]); break;
                    case "double": args[i] = Convert.ToDouble(args[i]); break;
                }

            return mi.Invoke(Missing.Value, args) + "";
        }
    }
}